
<?php
require_once("DatabaseConnect.php");
error_reporting(E_ALL ^ E_WARNING);
$con=Remoteconnect();
if($con==null){
	$con=Localconnect();	
}
$completed=0;



//Check if we should be updateing database:
//Get last update:
$LastUpdate="";
$result = mysqli_query($con,"SELECT * FROM  `time`");



while($row = mysqli_fetch_array($result)) {
	$LastUpdateString=$row['LastUpdate'];

  
}

$date = date('Y-m-d',  time());
$LastUpdate = date_create($LastUpdateString);
$lol= explode("-",$date);	
$date =date_create($date);
	

if($LastUpdate<$date){

//stoping the page from timeing out
set_time_limit(0);
$Symbols=array();
//Array of all the symbols from databse
$result = mysqli_query($con,"SELECT * FROM  `company info`");



while($row = mysqli_fetch_array($result)) {
	array_push($Symbols, $row['Symbol']);

  
}
$total = sizeof($Symbols);
$count=0;

foreach ($Symbols as $Symbol){
	$count+=1;
	$stopfirstDataline=0;

//initiating  cURL
$curl=curl_init();
//CSV URL obtains all the historical data from yahoo.

curl_setopt ($curl,CURLOPT_URL,"http://ichart.finance.yahoo.com/table.csv?s=".$Symbol."&a=".$lol[2] ."&b=".$lol[1]."&c=".$lol[0]."&d=11&e=6&f=2099");


curl_setopt ($curl,CURLOPT_HEADER,0);
ob_start();
curl_exec ($curl);
curl_close ($curl);
$data=ob_get_clean(); 
//Spltting the data into each days market data
$data=explode("\n",$data);


foreach ($data as $datalineresults){

	$stopfirstDataline++;
	
	$Date;
	$Open;
	$High;
	$Low;
	$Close;
	$Volume;
	
	if($stopfirstDataline>1){
	//splitting each days market data into variables
	$results=explode(",",$datalineresults);
	

    //Checks to make sure that the data to be added to the database is not NULL
	if(isset($results[0])&isset($results[1])&isset($results[2])&isset($results[3])&isset($results[4])&isset($results[5])){  

	$Date=$results[0];
	$Open=$results[1];
	$High=$results[2];
	$Low=$results[3];
	$Close=$results[4];
	$Volume=$results[5];
	//Execution of the variable	
	$sql="INSERT INTO `shares` (`Date`, `Symbol`, `Open`, `High`, `Low`, `Close`, `Volume`) VALUES ('$Date', '$Symbol', '$Open', '$High', '$Low', '$Close', '$Volume')";
	
	//error checking of sql queries
if (!mysqli_query($con,$sql))
{
 // echo('Error: ' . mysqli_error($con)."<br>");
}

	mysqli_query($con,$sql);


	

	if($Date==$LastUpdateString){
		break; //break if we have reached the last update date
	 }
	

	}

  	
	}
	


}
	

}
	$date = date('Y-m-d',  time());
	$sql="INSERT INTO `time` (`LastUpdate`) VALUES ('$date')";
	
	//error checking of sql queries
if (!mysqli_query($con,$sql))
{
  //echo('Error: ' . mysqli_error($con)."<br>");
}
}


?>
